import { NextResponse } from 'next/server'
import fs from 'fs'
import path from 'path'
export const runtime = 'nodejs'  // 强制该 API 路由在 Node.js 环境下运行

const ALLOWED_EXT = /\.(jpg|jpeg|png|gif|webp|svg|mp4|webm|ogg|mov|avi|mkv)$/i;
const VIDEO_EXT = /\.(mp4|webm|ogg|mov|avi|mkv)$/i;
const IMAGE_EXT = /\.(jpg|jpeg|png|gif|webp|svg)$/i;

export async function GET(req) {
  const { searchParams } = new URL(req.url);
  const page = parseInt(searchParams.get('page') || '1', 10);
  const pageSize = parseInt(searchParams.get('pageSize') || '12', 10);
  const type = searchParams.get('type');
  const dir = path.join(process.cwd(), 'uploads');
  let files = [];
  if (fs.existsSync(dir)) {
    files = fs.readdirSync(dir)
      .filter(name => {
        if (type === 'video') return VIDEO_EXT.test(name);
        if (type === 'image') return IMAGE_EXT.test(name);
        return ALLOWED_EXT.test(name);
      })
      .sort((a, b) => fs.statSync(path.join(dir, b)).mtimeMs - fs.statSync(path.join(dir, a)).mtimeMs)
      .map(name => {
        const filePath = path.join(dir, name);
        const stat = fs.statSync(filePath);
        let size = stat.size;
        let sizeStr = '';
        if (size < 1024) {
          sizeStr = size + 'B';
        } else if (size < 1024 * 1024) {
          sizeStr = (size / 1024).toFixed(1) + 'KB';
        } else {
          sizeStr = (size / 1024 / 1024).toFixed(2) + 'MB';
        }
        const pad = n => n.toString().padStart(2, '0');
        const d = stat.birthtime;
        const created_at = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
        let ext = path.extname(name).slice(1);
        let typeDisplay = ext.toUpperCase();
        return {
          url: `/api/files/${name}`,
          size: sizeStr,
          created_at,
          type: typeDisplay,
        };
      });
  }
  const total = files.length;
  const paged = files.slice((page - 1) * pageSize, page * pageSize);
  return NextResponse.json({ files: paged, total, code: 0, message: 'Success' });
}

export async function POST(req) {
  const codeMap = { 0: '上传成功', 1: '未上传文件', 2: '文件类型不支持', 3: '最大可上传单文件大小为20MB' };
  const formData = await req.formData();
  const file = formData.get('file');
  if (!file) { return NextResponse.json({ code: 1, codeMap, message: 'No file uploaded' }, { status: 400 }); }
  const buffer = Buffer.from(await file.arrayBuffer());
  const ext = path.extname(file.name) || '.jpg';
  if (!ALLOWED_EXT.test(ext)) { return NextResponse.json({ code: 2, codeMap, message: 'Only image and video files are supported' }, { status: 400 }); }
  if (buffer.length > 20 * 1024 * 1024) { return NextResponse.json({ code: 3, codeMap, message: 'The file is too large, with a maximum support of 20MB' }, { status: 400 }); }
  const fileName = `${Date.now()}_${Math.random().toString(36).slice(2)}${ext}`;
  const uploadDir = path.join(process.cwd(), 'uploads');
  if (!fs.existsSync(uploadDir)) fs.mkdirSync(uploadDir, { recursive: true });
  const filePath = path.join(uploadDir, fileName);
  fs.writeFileSync(filePath, buffer);
  const url = `/api/files/${fileName}`;
  return NextResponse.json({ code: 0, codeMap, message: 'File uploaded successfully', url });
}

export async function DELETE(req) {
  const codeMap = { 0: '删除成功', 1: '文件名不存在', 2: '未找到文件', 3: '删除失败' };
  const { filename } = await req.json();
  if (!filename) { return NextResponse.json({ code: 1, codeMap, message: 'Missing file name' }, { status: 400 }); }
  const filePath = path.join(process.cwd(), 'uploads', filename);
  try {
    if (fs.existsSync(filePath)) {
      fs.unlinkSync(filePath);
      return NextResponse.json({ code: 0, codeMap, message: 'File deleted successfully' });
    } else {
      return NextResponse.json({ code: 2, codeMap, message: 'File does not exist' }, { status: 404 });
    }
  } catch (e) {
    return NextResponse.json({ code: 3, codeMap, message: 'Error deleting file' }, { status: 500 });
  }
}